package cn.tedu.luban.worker.main.repository;

import cn.tedu.luban.passport.sdk.security.LubanSecurityContext;
import cn.tedu.luban.worker.main.converter.WorkerAreaConverter;
import cn.tedu.luban.worker.main.mapper.WorkerAreaMapper;
import cn.tedu.luban.worker.protocol.bo.WorkerAreaBO;
import cn.tedu.luban.worker.protocol.dos.WorkerAreaDO;
import cn.tedu.luban.worker.protocol.dos.WorkerDO;
import cn.tedu.luban.worker.protocol.param.WorkerRegistAreaParam;
import cn.tedu.luban.worker.protocol.param.WorkerRegistParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Repository
public class WorkerAreaRepoImpl implements WorkerAreaRepository{
    @Autowired
    private WorkerAreaMapper workerAreaMapper;
    @Override
    public void delete(Long userId) {

        //delete from worker_area where user_id=#{userId}
        workerAreaMapper.deleteByUserId(userId);
        String areaKey=WORKER_AREA_PREFIX+userId;
        redisTemplate.delete(areaKey);
    }
    @Autowired
    private WorkerAreaConverter workerAreaConverter;
    @Override
    public void saveWorkerAreas(WorkerRegistParam param) {
        //insert into worker_area (id,user_id,area_id,area_detail,通用字段)
        //values (第一个元素),(第二个元素)
        //1. 将入参 List<Area> 转化成 List<WorkerAreaDO> dos
        List<WorkerAreaDO> dos=
                workerAreaConverter.
                        params2dos(param.getWorkerRegistAreaParams(),param.getUserId());
        //2. 新增
        workerAreaMapper.batchInsert(dos);
    }
    private static final String WORKER_AREA_PREFIX="luban:worker:areas:";
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public List<WorkerAreaBO> findAreas(Long userId) {
        ListOperations listOperations = redisTemplate.opsForList();
        //缓存逻辑-读流程 key 使用userId value bos数组 redis中list数据格式保存缓存
        String areaKey=WORKER_AREA_PREFIX+userId;
        Boolean has = redisTemplate.hasKey(areaKey);
        List<WorkerAreaBO> bos;
        if (!has){
            List<WorkerAreaDO> dos=workerAreaMapper.selectByUserId(userId);
            bos=workerAreaConverter.dos2bos(dos);
            //lpush areaKey area1 area2
            //string hash list
            listOperations.rightPushAll(areaKey,bos);
            redisTemplate.expire(areaKey,60*60*24+new Random().nextInt(60*60*5), TimeUnit.SECONDS);
        }else{
            //lrange areaKey 0 -1 0 起始元素下标 -1 末尾
            bos=listOperations.range(areaKey,0,-1);
        }
        //select * from worker_area where user_id=#{}
        //返回的dos数组 转化成bo

        return bos;
    }
}
